<?php
namespace App\Service\Admin;

class StaffService extends BaseService
{
    //列表
    public static function index($pages, $pas)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbStaff);
//        if ($pas['role_id'] && $pas['role_id']>2) {
//            $db = $db->where('role_id', $pas['role_id']);
//        }
//        $db = $db->where('role_id', '>', 1);
//        if ($pas['depart_id']) {
//            $db = $db->where('depart_id', $pas['depart_id']);
//        } 
        if ($pas['role_id'] > 1) {
            $db = $db->where('id', '>', 1);
        }
        if ($pas['sort_id'] == 2) {
            $db = $db->orderBy('uptime', 'desc');
        } else {
            $db = $db->orderBy('uptime', 'asc');
        }
        if ($pas['kword']) {
            $db = $db->where('title', 'like', '%'.$pas['kword'].'%');
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])->get();
        if (!count($res)) {
            return self::toback(-2, '员工不存在');
        }
        $arys = [];
        foreach ($res as $v) {
            $roleOne = self::dbConn(self::$dbStRole)
                ->where('id', $v->role_id)
                ->first();
            $role_name = empty($roleOne) ? '-' : $roleOne->title;
            $departOne = self::dbConn(self::$dbStDepart)
                ->where('id', $v->depart_id)
                ->first();
            $depart_name = empty($departOne) ? '-' : $departOne->title;
            // $depart_name = $v->depart_lead==2 ? $depart_name.'【领导】' : $depart_name.'【成员】';
            $depart_lead_name = $v->depart_lead==2 ? '负责人' : '普通成员';
            $arys[] = [
                'id' => $v->id, 'title' => $v->title,
                'role_id' => $v->role_id, 'role_name' => $role_name,
                'depart_id' => $v->depart_id, 'depart_name' => $depart_name,
                'lasttime' => $v->uptime, 'is_able' => $v->is_able,
                'depart_lead' => $v->depart_lead,
                'depart_lead_name' => $depart_lead_name,
            ];
        }
        return self::toback(0, '', $arys, $total);
    }

    //选项
    public static function getOption()
    {
        $arys = ['role' => [], 'depart' => []];
        $arys['role'] = self::dbConn(self::$dbStRole)
            ->select('id', 'title')
            ->where('del', 0)
            // ->where('id', '>', 1)
            ->get();
        $arys['depart'] = self::dbConn(self::$dbStDepart)
            ->select('id', 'title')
            ->get();
        return self::toback(0, '', $arys);
    }

    //新增
    public static function add($pas)
    {
        $pas['addtime'] = $pas['uptime'] = toDate();
        $pas['passwd'] = md5('123456');
        if (in_array($pas['role_id'], [1,2,3,5])) {
            $pas['depart_lead'] = 2;
        } else {
            $pas['depart_lead'] = 1;
        }
        $res = self::dbConn(self::$dbStaff)
            ->where('title', $pas['title'])
            ->first();
        if (!empty($res)) {
            return self::toback(-2, '存在同名数据');
        }
        $res = self::dbConn(self::$dbStaff)->insertGetId($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    //新增
    public static function modify($id, $pas)
    {
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        // if (in_array($pas['role_id'], [1,2,3,5])) {
        //     $pas['depart_lead'] = 2;
        // } else {
        //     $pas['depart_lead'] = 1;
        // }
        $pas['uptime'] = toDate();
        $res = self::dbConn(self::$dbStaff)->where('id', $id)->update($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

//    //删除
//    public static function del($id)
//    {
//        $res = self::dbConn(self::$dbStaff)
//            ->where('del', 0)
//            ->where('id', $id)
//            ->first();
//        if (empty($res)) {
//            return self::toback(-2, '没有数据');
//        }
//        $res = self::dbConn(self::$dbStaff)
//            ->where('id', $id)
//            ->update(['del' => 1, 'deltime' => toDate()]);
//        if (!$res) {
//            return self::toback(-1, 'error');
//        }
//        return self::toback();
//    }

//    //删除
//    public static function del($id)
//    {
//        $res = self::dbConn(self::$dbStaff)
//            ->where('del', 0)
//            ->where('id', $id)
//            ->first();
//        if (empty($res)) {
//            return self::toback(-2, '没有数据');
//        }
//        $res = self::dbConn(self::$dbStaff)
//            ->where('id', $id)
//            ->update(['del' => 1, 'deltime' => toDate()]);
//        if (!$res) {
//            return self::toback(-1, 'error');
//        }
//        return self::toback();
//    }

    //启用禁用
    public static function toable($id, $able)
    {
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        if ($res->is_able == $able) {
            return self::toback(-2, '无需修改');
        }
        $pas['uptime'] = toDate();
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->update(['is_able' => $able, 'uptime' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    //重置密码
    public static function reset($id)
    {
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->update(['passwd' => md5('123456'), 'uptime' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    //修改密码
    public static function pwdModify($id, $pwd, $pwd2)
    {
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        if ($res->passwd != md5($pwd)) {
            return self::toback(-2, '原密码错误');
        }
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->update(['passwd' => md5($pwd2), 'uptime' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    // 设置密码
    public static function setPwd($id, $pas)
    {
        $res = (array) self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        if ($res['passwd'] != md5($pas['upwd'])) {
            return self::toback(-2, '原密码错误');
        }
        if ($pas['pwdNew'] != $pas['pwdNew2']) {
            return self::toback(-2, '2次新密码不一致');
        }
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->update(['passwd' => md5($pas['pwdNew']), 'uptime' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    /**
     * =======================
     * 一下是登录操作
     * =======================
     */

    //登录
    public static function dologin($uname, $upwd)
    {
        $loginMsg = ['uname' => $uname, 'upwd' => $upwd];
        $uOne = self::dbConn(self::$dbStaff)
            ->where('title', $uname)
            ->first();
        if (empty($uOne)) {
            self::addLog($loginMsg, 0, '员工不存在');
            return self::toback(-2, '员工不存在');
        }
        if ($uOne->is_able > 0) {
            self::addLog($loginMsg, 0, '员工被禁用');
            return self::toback(-2, '员工被禁用');
        }
        if ($uOne->passwd != md5($upwd)) {
            self::addLog($loginMsg, $uOne->id, '密码错误');
            return self::toback(-2, '密码错误');
        }
        if ($uOne->is_able) {
            self::addLog($loginMsg, $uOne->id, '员工已被禁用');
            return self::toback(-2, '员工已被禁用');
        }
        self::addLog($loginMsg, $uOne->id, '登录成功');
        $roleOne = self::dbConn(self::$dbStRole)
            ->where('id', $uOne->role_id)
            ->first();
        $role_name = empty($roleOne) ? '' : $roleOne->title;
        $departOne = self::dbConn(self::$dbStDepart)
            ->where('id', $uOne->depart_id)
            ->first();
        $depart_name = empty($departOne) ? '' : $departOne->title;
        $depart_name = $uOne->depart_lead==2 ? $depart_name.'负责人' : $depart_name.'普通成员';
        $ary = [
            'uid' => $uOne->id, 'uname' => $uname,
            'role_id' => $uOne->role_id, 'role_name' => $role_name,
            'depart_id' => $uOne->depart_id, 'depart_name' => $depart_name,
            'logtime' => date('Ymd', time()), 
            'is_leader' => $uOne->depart_lead>1 ? 1 : 0,
        ];
        return self::toback(0, '', $ary);
    }

    //登录日志
    public static function addLog($loginMsg = [], $uid = 0, $errMsg = '')
    {
        //$loginMsg = json_encode($loginMsg, 384);
        $loginMsg = json_encode($loginMsg, JSON_UNESCAPED_UNICODE);
        return self::dbConn(self::$dbStLogin)->insertGetId([
            'staff_id' => $uid, 'loginMsg' => $loginMsg,
            'errMsg' => $errMsg, 'addtime' => toDate(),
        ]);
    }

    //UID获取权限
    public static function leftMenu($pas)
    {
        //获取角色
        if ($pas['uid'] || $pas['role_id']) {
            $uOne = self::dbConn(self::$dbStaff)->where('id', $pas['uid'])->first();
            if (!$uOne) {
                return self::toback(-2, '员工不存在');
            }
            if (!$uOne->role_id) {
                return self::toback(-2, '员工角色不存在');
            }
        }
        $act_ids = []; //权限ID集合
        if ($pas['role_id'] > 2) {
            $authOnes = self::dbConn(self::$dbStAuth)
                ->where('del', 0)
                ->where('role_id', $pas['role_id'])
                ->get();
            if (!count($authOnes)) {
                return self::toback(-2, '权限不存在');
            }
            foreach ($authOnes as $v) {
                $act_ids[] = $v->action_id;
                $actOne = self::dbConn(self::$dbStAction)
                    ->where('id', $v->action_id)
                    ->first();
                if (!empty($actPone) || !in_array($actOne->pid, $act_ids)) {
                    $act_ids[] = $actOne->pid;
                }
            }
            if (!count($act_ids)) {
                return self::toback(-2, '没有权限');
            }
        }
        // 移除总经理的工时提报
        $actid_noin = [0];
        if ($pas['role_id'] == 2) {
            $actid_noin[] = 1;
        }
        // ddd($actid_noin);
        //获取权限
        if ($act_ids) {
            $actOnes = self::dbConn(self::$dbStAction)
                ->whereIn('id', $act_ids)
                ->where('pid', 0)
                ->whereNotIn('id', $actid_noin)
                ->get();
        } else {
            $actOnes = self::dbConn(self::$dbStAction)
                ->where('pid', 0)
                ->whereNotIn('id', $actid_noin)
                ->get();
        }
        if (!count($actOnes)) {
            return self::toback(-2, '菜单不存在');
        }
        $actArys = []; //权限ID集合
        $in_leads = []; //是否负责人任务
        foreach ($actOnes as $v) {
            if ($act_ids) {
                $childs = self::dbConn(self::$dbStAction)
                    ->whereIn('id', $act_ids)
                    ->where('pid', $v->id)
                    ->orderBy('sort', 'desc')
                    ->get();
            } else {
                $childs = self::dbConn(self::$dbStAction)
                    ->where('pid', $v->id)
                    ->orderBy('sort', 'desc')
                    ->get();
            }
            $childList = [];
            if (count($childs)) {
                foreach ($childs as $vv) {
                    $childList[] = [
                        'id' => $vv->id, 'title' => $vv->title,
                        'link' => $vv->link, 'pid' => $vv->pid,
                    ];
                    if (!in_array($vv->id, $in_leads)) {
                        $in_leads[] = $vv->id;
                    }
                }
            }
            if ($v->id == 1) { $icon = '&#xe62e;'; }
            else { $icon = '&#xe616;'; }
            $actArys[] = [
                'id' => $v->id, 'title' => $v->title,
                'link' => $v->link, 'childs' => $childList,
                'icon' => $icon,
            ];
        }
        // // 给负责人，默认加上任务权限
        // if ($pas['is_leader'] && !in_array(5, $in_leads)) {
        //     foreach ($actArys as $k => $v) {
        //         if ($v['id'] == 1) {
        //             foreach ($v['childs'] as $kk => $vv) {
        //                 $leadOne = (array) self::dbConn(self::$dbStAction)
        //                     ->where('id', 5)
        //                     ->first();
        //                 $actArys[$k]['childs'][] = [
        //                     'id' => $leadOne['id'], 'title' => $leadOne['title'],
        //                     'link' => $leadOne['link'], 'pid' => $leadOne['pid'],
        //                 ];
        //             }
        //         }
        //     }
        // }
        return self::toback(0, '', $actArys);
    }
}